package dao

import (
	"context"
	"mini-app/internal/dal"
	"mini-app/internal/models"
	"strings"
	"time"

	"192.168.1.75/go-pkg/helper"
	"gorm.io/gorm"
)

type PublishDevice struct{}

func (PublishDevice) Create(ctx context.Context, db *gorm.DB, robotName, groupID string) (err error) {
	m := dal.Use(db).PublishDevice
	var d models.PublishDevice
	d.ID, _ = helper.UUID{}.String()
	d.RobotName = robotName
	d.GroupID = groupID
	d.CreatedAt = time.Now().Unix()
	d.DeletedAt = 0
	m.WithContext(ctx).Create(&d)
	return
}

func (PublishDevice) GetDeviceListByGroupID(ctx context.Context, db *gorm.DB, groupID string) (data []*models.PublishDevice, count int64) {
	m := dal.Use(db).PublishDevice
	tx := m.WithContext(ctx)
	if groupID != "" {
		tx = tx.Where(m.GroupID.Eq(groupID))
	}

	list, _ := tx.Find()
	count, _ = tx.Count()
	return list, count
}

func (PublishDevice) GetRobotNameList(ctx context.Context, db *gorm.DB, groupID string) (list []string) {
	m := dal.Use(db).PublishDevice
	tx := m.WithContext(ctx)
	if groupID != "" {
		tx = tx.Where(m.GroupID.Eq(groupID))
	}
	tx.Pluck(m.RobotName, &list)
	return
}

func (PublishDevice) GroupRobotCount(ctx context.Context, db *gorm.DB, groupID string) (res []struct {
	GroupID     string `gorm:"column:group_id;"`
	DeviceCount int64  `gorm:"column:device_count"`
}) {
	m := dal.Use(db).PublishDevice
	tx := m.WithContext(ctx)
	if groupID != "" {
		if strings.Contains(groupID, ",") {
			tx = tx.Where(m.GroupID.In(strings.Split(groupID, ",")...))
		} else {
			tx = tx.Where(m.GroupID.Eq(groupID))
		}
	}
	tx.Select(m.GroupID, m.ID.Count().As("device_count")).
		Group(m.GroupID).
		Scan(&res)
	return
}

// 删除设备
func (PublishDevice) DeleteGroupDevice(ctx context.Context, db *gorm.DB, groupID string, deleteDevice string) (err error) {
	m := dal.Use(db).PublishDevice
	m.WithContext(ctx).
		Where(m.GroupID.Eq(groupID)).
		Where(m.RobotName.In(strings.Split(deleteDevice, ",")...)).
		Delete(&models.PublishDevice{})
	return
}

// 根据机器人名称获取所属分组ID列表
func (PublishDevice) GetGroupIDsByRobotName(ctx context.Context, db *gorm.DB, robotName string) (groupIDs []string) {
	m := dal.Use(db).PublishDevice
	tx := m.WithContext(ctx).
		Where(m.DeletedAt.Eq(0)).
		Where(m.RobotName.Eq(robotName))
	tx.Pluck(m.GroupID, &groupIDs)
	return
}
func (PublishDevice) GetGroupIDsByRobotNames(ctx context.Context, db *gorm.DB, robotNames string) (groupIDs []string) {
	m := dal.Use(db).PublishDevice
	tx := m.WithContext(ctx)

	tx1 := tx.Where(m.DeletedAt.Eq(0))

	robotNamesSep := strings.Split(robotNames, ",")

	tx2 := m.WithContext(ctx)
	for _, robotName := range robotNamesSep {
		tx2 = tx2.Or(m.RobotName.Eq(robotName))
	}
	tx = tx.Where(tx1).Where(tx2)
	tx.Pluck(m.GroupID, &groupIDs)
	return
}
